<template>
    <el-row class="test-paper-detail">
        <div class="add-type">
            <span>{{form.id!=='add'?'修改试卷模板':'新建试卷模板'}}</span>
            <el-button @click="addTypeFun" v-if="form.id==='add'">引用已有模版</el-button>
        </div>
        <el-form ref="form" v-show="!addType" class="o-form" label-position="right" label-width="120px" :model="form" :rules="rules">
            <el-form-item prop="rangeType">
                <div slot="label" class="tow-four">
                    类
                    <span>型:</span>

                </div>
                <el-select v-model="form.rangeType" placeholder="">
                    <el-option label="标准" :value="0"></el-option>
                    <el-option label="自定义" :value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="style" label="报告样式:">
                <el-select v-model="form.style" placeholder="">
                    <el-option label="标准版" :value="1"></el-option>
                    <el-option label="文综版" :value="2"></el-option>
                    <el-option label="语文版" :value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="dataSubject">
                <div slot="label" class="tow-four">
                    科
                    <span>目:</span>

                </div>

                <el-select v-model="form.dataSubject" placeholder="">
                    <el-option v-for="(subject,index) in condition.subjectList" :label="subject.name" :value="subject.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="baseSectionId">
                <div slot="label" class="tow-four">
                    年
                    <span>级:</span>

                </div>
                <el-select v-model="form.baseSectionId" placeholder="">
                    <el-option v-for="(grade,index) in condition.gradeObj.list" :label="grade.name" :value="grade.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区分文理:" prop="wal">
                <el-select v-model="form.wal" placeholder="">
                    <el-option label="通用" :value="0"></el-option>
                    <el-option label="文科" :value="1"></el-option>
                    <el-option label="理科" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="baseTrimesterId">
                <div slot="label" class="tow-four">
                    学
                    <span>期:</span>

                </div>

                <el-select v-model="form.baseTrimesterId" placeholder="">
                    <el-option v-for="(term,index) in condition.termObj.list" :label="term.name" :value="term.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="baseLevelId" v-if="form.rangeType!==1">
                <div slot="label" class="tow-four">
                    班
                    <span>型:</span>

                </div>

                <el-select v-model="form.baseLevelId" placeholder="">
                    <el-option v-for="(level,index) in condition.levelObj.list" :label="level.name" :value="level.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="试卷类型:" prop="dataTimeType">
                <el-select v-model="form.dataTimeType" placeholder="">
                    <el-option v-for="(mater,index) in condition.termTypeList" :label="mater.name" :value="mater.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="score" v-if="form.id!=='add'">
                <div slot="label" class="tow-four">
                    试卷总分:</span>
                </div>
                <el-input :disabled="true" type="number" v-model.number="form.score" placeholder="请填写正整数0－200内数值"></el-input>
            </el-form-item>
            <el-form-item label="试卷名称:" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item>
                <div slot="label" class="tow-four">
                    试卷时间:</span>

                </div>
                <el-input type="number" v-model="form.examTime" placeholder="分钟"></el-input>
            </el-form-item>
            <el-form-item label="试卷简介:">
                <el-input type="textarea" :rows="6" v-model="form.intro"></el-input>
            </el-form-item>
            <el-form-item class="opt-btn">
                <el-button v-if="!isView" :disabled="addDisabled" type="primary" class="height-btn" @click="sure">确定</el-button>
                <el-button class="light-btn" @click="$router.go(-1)">{{isView?'返回':'取消'}}</el-button>
            </el-form-item>
        </el-form>
        <div calss="add-has">
            <el-dialog title="引用已有试卷模板" :visible.sync="dialogTableVisible" @close="checkItem={}" class="add-has">
                <div class="has-course">
                    <el-form :inline="true" :model="sForm" class="t-form">
                        <el-form-item label="">
                            <el-select v-model="sForm.baseSectionId" placeholder="年级">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="(grade,index) in condition.gradeObj.list" :label="grade.name" :value="grade.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-select v-model="sForm.dataSubject" placeholder="科目">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="(subject,index) in condition.subjectList" :label="subject.name" :value="subject.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-select v-model="sForm.baseTrimesterId" placeholder="学期">
                                <el-option label="全部" value=""></el-option>
                                <el-option v-for="(term,index) in condition.termObj.list" :label="term.name" :value="term.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-input v-model="sForm.name" placeholder="请输入试卷模板名称"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="search" class="search-btn">查询</el-button>
                        </el-form-item>
                    </el-form>
                    <div class="search-table">
                        <el-table class="line-table" :data="result.list" header-align="center" empty-text="暂无试卷模版">
                            <el-table-column label="" align="center" width="60">
                                <template scope="scope">
                                    <el-radio :label="scope.row.id" v-model="checkItem" class="table-radio"></el-radio>
                                </template>
                            </el-table-column>
                            <el-table-column prop="name" label="试卷名称" align="center"></el-table-column>
                            <el-table-column prop="baseLevel" label="班型" align="center"></el-table-column>
                            <el-table-column prop="subjectName" label="科目" align="center"> </el-table-column>
                            <el-table-column label="类型" align="center">
                                <template scope="scope">
                                    {{scope.row.rangeType===0?'标准':'自定义'}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="baseSection" label="年级" align="center"> </el-table-column>
                            <el-table-column prop="baseTrimester" label="学期" align="center"> </el-table-column>
                            <el-table-column prop="dataTimeTypeName" label="试卷类型" align="center"> </el-table-column>
                        </el-table>
                        <v-pagination ref="pagin" class="pag" :total="result.total|toNumber" :pageSize="sForm.pageSize" @getListResult="getExamList" :currentPage="sForm.pageIndex"></v-pagination>
                        <div class="opt-btn has-course-btn">
                            <el-button class="height-btn" @click="saveExisting">确定</el-button>
                        </div>
                    </div>
                </div>
            </el-dialog>
        </div>

    </el-row>
</template>
<script>
import storage from '../../lib/storage/index'
import Upload from '../common/Upload'
import VPagination from '../common/Pagination'
import { mapState, mapActions } from 'vuex'
import io from 'lib/io'
export default {
    components: {
        Upload,
        VPagination
    },
    data() {
        return {
            addDisabled: false,
            activeName: this.$route.query.activeName,
            isView: this.$route.query.isView === 'isView',
            rangeType: 1,
            form: {
                examModelActivityId: this.$route.query.activeId,
                id: this.$route.params.id,
                rangeType: '',
                name: '',
                baseSectionId: '',
                wal: '',
                dataSubject: '',
                baseTrimesterId: '',
                baseLevelId: '',
                score: null,
                examTime: '',
                intro: '',
                style: 1
            },
            rules: {
                rangeType: [{ required: true, message: '请选择类型！', trigger: 'change' }],
                style: [{ required: true, message: '请选择报告样式！', trigger: 'change' }],
                name: [{ required: true, message: '试卷名称不能为空！', trigger: 'change' }, { max: 40, message: '试卷名称不能超过40字', trigger: 'change' }],
                baseSectionId: [{ required: true, message: '请选择年级！', trigger: 'change' }],
                wal: [{ required: true, message: '请选择文理科！', trigger: 'change' }],
                dataSubject: [{ required: true, message: '请选择科目！', trigger: 'change' }],
                baseLevelId: [{ required: true, message: '请选择班型！', trigger: 'change' }],
                dataTimeType: [{ required: true, message: '请选择试卷类型！', trigger: 'change' }],
                score: [
                    { required: true, message: '试卷总分不能为空！', trigger: 'change' },
                    { type: 'number', message: '试卷总分必须为数值' }
                ],
                examTime: [
                    { type: 'number', message: '试卷总分必须为数值' }
                ],
                intro: [
                    { max: 200, message: '试卷简介不能超过200字', trigger: 'change' }
                ],
                baseTrimesterId: [{ required: true, message: '请选择学期！', trigger: 'change' }]
            },
            sForm: {
                examModelActivityId: this.$route.query.activeId,
                isRelated: '1',
                name: '',
                baseTrimesterId: null,
                dataSubject: null,
                baseSectionId: null,
                status: 1,
                pageIndex: 1,
                pageSize: 5
            },
            addType: false,
            dialogTableVisible: false,
            checkItem: {},
            closeCheckItem: {}
        }
    },
    computed: {
        ...mapState(['condition', 'exam']),
        ...mapState({ result: state => state.exam.exam })
    },
    watch: {
        'form.wal'(val, oldVal) {
            if (this.form.id !== 'add' && !oldVal) {
                return
            }
            this.changeName()
        },
        'form.baseLevelId'(val, oldVal) {
            if (this.form.id !== 'add' && !oldVal) {
                return
            }
            this.changeName()
        },
        'form.rangeType'(val, oldVal) {
            if (this.form.id !== 'add' && !oldVal) {
                return
            }
            this.changeName()
        },
        'form.baseSectionId'(val, oldVal) {
            if (this.form.id !== 'add' && !oldVal) {
                return
            }
            this.changeName()
        },
        'form.dataSubject'(val, oldVal) {
            this.findBaseSectionPage({ pageIndex: 1, pageSize: 1000000, subjectId: this.form.dataSubject })
            if (this.form.id !== 'add' && !oldVal) {
                return
            }
            this.changeName()
        },
        'sForm.dataSubject'(val) {
            this.findBaseSectionPage({ pageIndex: 1, pageSize: 1000000, subjectId: this.sForm.dataSubject })
        },
        'exam.examDetail'(val) {
            if (this.form.id === 'add') {
                this.form = { ...val, id: 'add', examModelActivityId: this.$route.query.activeId }
            } else {
                this.form = { ...val }
                this.rangeType = val.rangeType
            }
            this.$refs.form.clearValidate()
        }
    },
    created() {
        if (this.form.id !== 'add') {
            this.detailExamModel({ id: this.form.id })
        }
        this.findBaseSectionPage({ pageIndex: 1, pageSize: 1000000, subjectId: this.form.dataSubject })
        this.findBaseTermPage({ pageIndex: 1, pageSize: 1000000 })
        this.findSubjectsData({ sectionId: this.form.baseSectionId })
        this.findBaseLevelPage({ pageIndex: 1, pageSize: 1000000 })
        this.findTimeTypeData({})
        this.findYearsData()
    },
    methods: {
        ...mapActions(['findBaseSectionPage', 'findSubjectsData', 'findBaseTermPage', 'findBaseLevelPage', 'findYearsData', 'findTimeTypeData', 'examModelList', 'detailExamModel']),
        changeName() {
            if (this.form.rangeType === 0) {
                let grade = ''
                let subject = ''
                let level = ''
                let wal = this.form.wal === 0 ? '通用' : this.form.wal === 1 ? '文科' : this.form.wal === 2 ? '理科' : ''
                this.condition.gradeObj.list.map((item, i) => {
                    if (item.id === this.form.baseSectionId) {
                        grade = item.name
                    }
                })
                this.condition.subjectList.map((item, i) => {
                    if (item.id === this.form.dataSubject) {
                        subject = item.name
                    }
                })
                this.condition.levelObj.list.map((item, i) => {
                    if (item.id === this.form.baseLevelId) {
                        level = item.name
                    }
                })
                this.form.name = grade + subject + level + wal
            } else {
                let grade = ''
                let subject = ''
                let wal = this.form.wal === 0 ? '通用' : this.form.wal === 1 ? '文科' : this.form.wal === 2 ? '理科' : ''
                let account = storage.getCurrentUserInfo() ? storage.getCurrentUserInfo().userName : ''
                this.condition.gradeObj.list.map((item, i) => {
                    if (item.id === this.form.baseSectionId) {
                        grade = item.name
                    }
                })
                this.condition.subjectList.map((item, i) => {
                    if (item.id === this.form.dataSubject) {
                        subject = item.name
                    }
                })
                this.form.name = grade + subject + wal + '(' + account + ')'
            }
        },
        uploadSuccess(url, size, duration, originName) {
            this.form.videoUrl = url
            this.form.videoName = originName
            this.form.videoSize = size
        },
        //搜索试卷膜拜列表
        search() {
            this.$refs.pagin.changePage(1)
            this.sForm.pageIndex = 1
            this.getExamList()
        },
        //获取试卷模版列表
        getExamList(opt) {
            this.examModelList({ ...this.sForm, ...opt, pageSize: this.sForm.pageSize })
        },
        onSubmit() {

        },
        addTypeFun() {
            // this.addType = true
            this.getExamList(this.sForm)
            setTimeout(() => {
                this.dialogTableVisible = true
            }, 300);
        },
        //保存新建试卷
        sure() {
            this.addDisabled = true
            setTimeout(() => {
                this.addDisabled = false
            }, 2000)
            this.$refs.form.validate(async (vali) => {
                if (this.form.score > 200 || this.form.score < 0) {
                    this.$message('试卷总分范围为0～200')
                    return
                }
                if (this.form.intro && this.form.intro.length > 200) {
                    this.$message('试卷简介长度在200内')
                    return
                }
                if (this.form.examTime < 0) {
                    this.$message('试卷时间不能为负数')
                    return
                }
                if (vali) {
                    if (!String.trim(this.form.name).length) {
                        this.$message('名称不允许只输入空格')
                        return
                    }
                    if (this.form.id != 'add' && this.form.rangeType !== 1 && this.form.rangeType !== this.rangeType) {
                        let { data } = await io.post6(io.existExamModelRange, { id: this.form.id })
                        if (data.success) {
                            if (data.data > 0) {
                                this.$confirm('该试卷已配置了自定义班级，如更改将清除数据且操作不可逆，是否确认', '提示').then(() => {
                                    this.addOrUpdateModule()
                                }).catch((err) => {
                                    console.log('取消')
                                })
                            } else {
                                this.addOrUpdateModule()
                            }
                        }
                    } else {
                        this.addOrUpdateModule()
                    }
                } else {
                    this.$message('您还有必填项未填！')
                    return
                }
            })
        },
        saveExisting() {
            if (JSON.stringify(this.checkItem) === '{}') {
                this.$message('请选择试卷模版')
                return
            }
            this.closeCheckItem = this.checkItem
            this.detailExamModel({ id: this.checkItem })
            this.dialogTableVisible = false
        },

        async addOrUpdateModule() {
            let id = this.form.id === 'add' ? '' : this.form.id
            let url = this.form.id === 'add' ? io.addExamModel : io.editExamModel
            let { data } = await io.post6(url, { ...this.form, id, pId: this.closeCheckItem })
            if (data.success) {
                this.$message({ message: '保存成功', type: 'success' })
                // this.$router.go(-1)
                if (this.form.id === 'add') {
                    this.$router.push({ path: '/main/exam/add-module', query: { id: data.data.id, rangeType: data.data.rangeType, activeId: this.form.examModelActivityId, activeName: this.activeName } })
                } else {
                    this.$router.go(-1)
                }
            }
        }
    }
}
</script>
<style lang="stylus" scoped>
@import '~assets/stylus/mixin.styl'
.test-paper-detail
    .has-course-btn
        margin-top 30px
    .add-type
        height 45px
        line-height 45px
        // margin 15px 50px 0
        margin-top 30px
        text-align left
        button
            float right 
            margin-top 7.5px
        .el-button
            background #1ebd99
            color #ffffff
            font-size 14px
            border 1px solid #1ebd99
            border-radius 15px
            height 30px
    .gray
        table-form()
        padding-top 15px
        padding-right 20px
        padding-bottom 10px
        .el-form-item
            margin-bottom 0
    .o-form
        padding 0 200px
        margin auto
        margin-top 50px
        .el-select
            width 100%
            
    .head
      margin-top 10px
    .free-num
        margin-left 10px
        font-style normal
    .personal
        border 0
        color #606266
        &:hover
            background transparent
    .opt-btn
        text-align center
        margin-top 40px
    .surport
        color #ff7800
        padding-left 40px
.has-course
    // padding 20px 50px 
    .t-form
      padding 22px 20px 0 20px
      background #f7f7f7
      .el-select
        width 120px
    .search-table
      padding 20px 20px 0 20px

</style>
<style lang="stylus">
.data-detail .gray
    .el-form-item__label,.el-form-item__content
        line-height 30px
        font-size 14px
        font-weight normal 
.table-radio
    .el-radio__label
        display none
.add-has
    .el-dialog
        width 60%
        min-width 740px


</style>


